package com.example.mqttdemo.listener;

import com.example.mqttdemo.properties.MqttConfigurationProperties;
import jakarta.annotation.PostConstruct;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class MqttSubscriber {
    @Autowired
    private MqttClient mqttClient;

    @Autowired
    private MqttMessageListener messageListener;

    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;

    @EventListener(ApplicationReadyEvent.class)
    public void subscribe() {
        try {
            mqttClient.subscribe(mqttConfigurationProperties.getSubTopic(), messageListener);
            System.out.println("已订阅MQTT主题: " + mqttConfigurationProperties.getSubTopic());
        } catch (MqttException e) {
            System.err.println("订阅MQTT主题失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
